package com.icode.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.icode.common.constant.AuthServerConstant;
import com.icode.common.utils.HttpUtils;
import com.icode.common.utils.R;
import com.icode.common.vo.MemberResponseVo;
import com.icode.gulimall.auth.feign.MemberFeignService;
import com.icode.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2021-01-06 14:48
 */
@Controller
public class OAuthController {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String authWeibo(@RequestParam("code") String code, HttpSession httpSession) {

        String host = "https://api.weibo.com";
        String path = "/oauth2/access_token";
        String method = "post";

        Map<String, String> querys = new HashMap<>();
        querys.put("client_id", "229256400");
        querys.put("client_secret", "69ea48588f8b1e2da54690de98e72925");
        querys.put("grant_type", "authorization_code");
        querys.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        querys.put("code", code);

        SocialUser socialUser = null;
        try {
            HttpResponse httpResponse = HttpUtils.doPost(host, path, method, new HashMap<>(), querys, new HashMap<>());

            if (httpResponse.getStatusLine().getStatusCode() == 200){
                String jsonString = EntityUtils.toString(httpResponse.getEntity());
                socialUser = JSON.parseObject(jsonString, SocialUser.class);
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //远程调   社交登录
        R r = memberFeignService.oauthLogin(socialUser);
        if (r.getCode()==0){
            MemberResponseVo respVo = r.getData("data", new TypeReference<MemberResponseVo>() {
            });
//            Cookie jsessionid = new Cookie("JSESSIONID", "");
//            jsessionid.setDomain("gulimall.com");
//            httpServletResponse.addCookie(jsessionid);

            //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
            //以后浏览器访问哪个网站就会带上这个网站的cookie
            // 1、默认发的令牌。当前域（解决子域session共享问题）
            // 2、使用JSON的序列化方式来序列化对象到Redis中
            httpSession.setAttribute(AuthServerConstant.LOGIN_USER, respVo);
            return "redirect:http://gulimall.com";
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
